import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus';
// import JSEncrypt from 'jsencrypt';
// import { encryptDes, decryptDes } from '../plugins/des';
import { useMainStore } from '../store/index';
// import router from '../router/index';

const instance = axios.create({
	baseURL: import.meta.env.VITE_API_URL,
	timeout: 60000,
});

let loading;
// 正在请求的数量
let requestCount = 0;
// 显示loading
const showLoading = () => {
	if (requestCount === 0) {
		loading = ElLoading.service({
			lock: true,
			text: 'Loading',
			background: 'rgba(0, 0, 0, 0.7)',
		});
	}
	requestCount++;
};
// 隐藏loading
const hideLoading = () => {
	requestCount--;
	if (requestCount === 0) {
		loading.close();
	}
};

// 请求拦截器
instance.interceptors.request.use(
	(config) => {
		console.log(`请求的url----${config.url}`, config.data);

		const store = useMainStore();
		config.headers.token = store.token || '';

		return config;
	},
	(error) =>
		// 对请求错误做些什么
		Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
	(response) => {
		console.log('res====响应数据====', response);
		// hideLoading()

		// 响应成功
		return response.data;
	},
	(error) => {
		console.log(error, '请求拦截');
		// 从pendingRequest对象中移除请求

		// 响应错误
		if (error.response && error.response.status) {
			const { status } = error.response;
			let message1 = '';
			const actions = {
				400: '请求错误',
				401: '请求错误',
				404: '请求地址出错',
				408: '请求超时',
				500: '服务器内部错误!',
				501: '服务未实现!',
				502: '网关错误!',
				503: '服务不可用!',
				504: '网关超时!',
				505: 'HTTP版本不受支持',
				20000: '请求失败',
			};
			message1 = actions[status] ? actions[status] : actions['20000'];
			// console.log(message1);
			// message.error(message1);
			ElMessage.error(message1);
			return Promise.reject(error);
		}
		return Promise.reject(error);
	}
);

const request = (
	url,
	data = {},
	isloading = false,
	method = 'POST',
	type = null,
	timeout = 60000,
	headers = { 'X-Custom-Header': 'foobar', 'content-type': 'application/json' }
) => {
	!isloading && showLoading(); //todo 也可以放到请求拦截的里面中，这里更方便的进行控制
	return new Promise((resolve, reject) => {
		instance({
			method: method,
			url: url,
			data,
			headers,
			responseType: type != null ? type : 'json',
			timeout,
		})
			.then((res) => {
				console.log('请求结果', res);
				// if (res.hasOwnProperty('code') && res.code === 403) {
				// 	//token过期
				// 	const store = useMainStore();
				// 	message.error(res.msg);
				// 	store.token = '';
				// 	store.userInfo = {};
				// 	console.log(router, '路由');
				// 	router.replace('/login');

				// 	return;
				// }

				resolve(res);
			})
			.catch((error1) => {
				console.log('失败-------', error1);

				reject(error1);
			})
			.finally(() => {
				!isloading && hideLoading(); //todo 这个可以放到响应拦截器中，这里进行方便的控制
			});
	});
};

export default request;
